<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isFinishLoading"
      success-text="刷新成功"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell
          v-for="(article, index) in articles"
          :key="index"
          :title="article.title"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article";

export default {
  name: "ArticleList",
  components: {},
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      finisheCount: 0,
      articles: [],
      loading: false,
      finished: false,
      isFinishLoading: false,
      timestamp: null
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    onRefresh() {
      //下拉刷新，组件会自动展示 loding 状态
      // 获取Promise对象数据方式 一
      //1.请求获取数据
      let rs = getArticles({
        channel_id: this.channel.id,
        timestamp: Date.now(),
        with_top: 1
      });

      rs.then(data => {
        //2.把数据往数组 articles 头部加
        console.log(data.data.data.results);
        this.articles.unshift(...data.data.data.results);
      });
      // 3.就是关闭加载状态
      this.isFinishLoading = false;
    },
    async onLoad() {
      //1.获取请求数据
      let { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: this.timestamp || Date.now(),
        with_top: 1
      });
      //console.log(data.data.results);
      //2.把数据放到 list 数组中
      this.articles.push(...data.data.results);
      //3. 加载状态结束
      this.loading = false;
      // 数据全部加载完成
      if (!data.data.results) {
        //如果没有数据了
        this.finished = true;
      } else {
        //还有数据
        this.timestamp = data.data.timestamp;
      }
    }
  }
};
</script>

<style scoped lang="less">
.article-list {
  overflow-y: auto;
  position: fixed;
  top: 180px;
  left: 0;
  right: 0;
  bottom: 90px;
}
</style>